<?php
class CacheRedis{
    private static $cacher = null;
    private $rdCacher;
    private $outTime;
    private $pre;
    private function __construct($conf){
//        $conf=>[
//            "type"=>"reids",
//            "host"=>"127.0.0.1",
//            "port"=>"6379",
//            "database"=>"1",
//            "pre"=>"mtfy_",
//            "outtime"=>40,
//        "pass"=>"",
//        ]
        $this->outTime=@$conf["outtime"]?$conf["outtime"]:3600;
        $this->rdCacher = new \redis();
        $this->rdCacher->connect($conf['host'], $conf['port']);
        if(@$conf["pass"]){
            try {
                $this->rdCacher->auth($conf["pass"]);
            } catch (RedisException $e) {
                die("redis链接错误:".$e->getMessage());
            }
        }
        if(@$conf["database"]){
            $this->rdCacher->select($conf["database"]);
        }
        $this->pre = $conf['pre'];
    }

    public static function new($conf){
        if(!$conf){
            $conf=".cache";
        }
        if(function_exists("Config")){
            $conf=Config($conf);
        }else{
            throw new Exception("缓存配置错误");
        }
        if(self::$cacher == null){self::$cacher = new CacheRedis($conf);}
        return self::$cacher;
    }
    public static function newc($conf){
        if(self::$cacher == null){self::$cacher = new CacheRedis($conf);}
        return self::$cacher;
    }
    public function get($name){
        $cacheData = $this->rdCacher->get($this->pre.$name);
        if(empty($cacheData)){return null;}
        return unserialize($cacheData);
    }

    public function set($name, $val, $expire = null){
        if(!$expire){
            $expire=$this->outTime;
        }
        if($val===null){
            $this->remove($name);
            return;
        }
        if($expire > 2592000){$expire = 2592000;}
        $this->rdCacher->setex($this->pre.$name, $expire, serialize($val));
    }

    public function remove($name){
        $this->rdCacher->del($this->pre.$name);
    }

    public function clear(){
        $this->rdCacher->flushAll();
    }

    public function close(){
        $this->rdCacher->close();
    }
}